import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import type { AxiosResponse } from 'axios'
import type { ApiResponse } from '@/utils/request'

// 定义历史消息的类型
export interface HistoryMessage {
  role: "user" | "assistant";
  content: string;
}

// 创建专门的AI聊天请求实例
const chatRequest = axios.create({
  baseURL: '/api',
  timeout: 120000,  // 120秒超时
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 添加请求拦截器
chatRequest.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `logos ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
chatRequest.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    if (!res.success && res.message) {
      ElMessage.error(res.message)
      return Promise.reject(new Error(res.message || 'Error'))
    }
    return res
  },
  (error) => {
    if (error.message.includes('timeout')) {
      ElMessage.error('AI响应超时，请重试')
    } else {
      ElMessage.error('请求失败，请重试')
    }
    return Promise.reject(error)
  }
)

// 发送聊天消息
export const sendChatMessage = (message: string, chatId: string) => {
  console.log('发送请求参数:', { message, chatId });
  return chatRequest({
    url: '/user/tourist/ai',
    method: 'post',
    data: {
      message,
      chatId
    }
  }) as Promise<ApiResponse<string>>;
};

// 获取历史会话列表
export const getChatHistory = () => {
  return chatRequest({
    url: '/ai/history',
    method: 'get'
  }) as Promise<ApiResponse<string[]>>;
}; 

// 获取指定会话的历史聊天记录
export const getChatHistoryById = (chatId: string) => {
  return chatRequest({
    url: `/ai/history/${chatId}`,
    method: 'get'
  }) as Promise<ApiResponse<HistoryMessage[]>>;
};